package com.parrots.sample.aop;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.security.GrantedAuthority;

import com.parrots.sample.entity.Resource;
import com.parrots.sample.entity.Role;
import com.parrots.sample.entity.User;
import com.parrots.sample.security.support.SecurityUserHolder;

public class MenuLoadingAdvice implements AfterReturningAdvice {

    @SuppressWarnings("unchecked")
    @Override
    public void afterReturning(Object returnValue, Method method,
            Object[] args, Object target) throws Throwable {
        List<Resource> menus = (List<Resource>) returnValue;
        List<Resource> grantedMenus = new ArrayList<Resource>();
        User currentUser = SecurityUserHolder.getCurrentUser();
        GrantedAuthority[] authorities = currentUser.getAuthorities();
        
        for (GrantedAuthority grantedAuthority : authorities) {
            for (Resource resource : menus) {
                Set<Role> grantedRoles = resource.getRoles();
                if (grantedRoles.contains(grantedAuthority))
                    grantedMenus.add(resource);
            }
        }
        
        returnValue = grantedMenus;
    }

}
